package dispatcher;

import org.json.JSONException;

import exceptions.ExDBException;

import services.PollService;
import services.ValidationService;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SaveGrid extends HttpServlet{

	private static final long serialVersionUID = -3880714005446692536L;

	private static final String GET_VALIDATION_ERRORS = "GET_VE";
	@SuppressWarnings("unused")
	private static final String GET_COMPANY_CAMPAIGNS = "GET_CC";
	private static final String GET_REJECT_COMMENTS = "GET_RC";
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			saveGrid(req, resp);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			saveGrid(req, resp);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	protected void saveGrid(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, JSONException {
		HttpSession session = request.getSession(true);
		Object userID = session.getAttribute("userID");
//		Object sessionCompanyCampaignID = session.getAttribute("companyCampaign");
		if(userID == null || userID.toString().trim().length() == 0)
		{
			response.sendRedirect("./login");
		}
		else
		{
			String prefix = request.getParameter("gridName");
			Long objectID = Long.valueOf(request.getParameter("id"));
			
			if(prefix.equals(GET_VALIDATION_ERRORS))
			{
				String observations = request.getParameter("observation");
				Long reasonID = Long.valueOf(request.getParameter("reason"));
				ValidationService validationService = new ValidationService();
				try {
					validationService.saveValidationErrorByID(objectID,reasonID, observations);
				} catch (ExDBException e) {
					//TODO Ver como manejar el error!
					e.printStackTrace();
				}
			}
			else if(prefix.equals(GET_REJECT_COMMENTS))
			{
				String observations = request.getParameter("Observation");
				PollService pollService = new PollService();
				try {
					pollService.saveRejectCommentByID(objectID, Long.valueOf(userID.toString()), observations);
				} catch (ExDBException e) {
					//TODO Ver como manejar el error!
					e.printStackTrace();
				}
				
			}
		}
	}
}
